#include "client.h"

int doRegister(int sockfd){
    char username[50]={0};
    char password[50]={0};
    printf("please input username:");
    fflush(stdout);
    int ret=read(STDOUT_FILENO,username,sizeof(username));
    username[--ret]='\0';
    printf("please input password:");
    fflush(stdout);
    ret=read(STDOUT_FILENO,password,sizeof(password));
    password[--ret]='\0';
    
    // 发送用户名
    commandPacket_t usernameInfo;
    bzero(&usernameInfo,sizeof(usernameInfo));
    usernameInfo.cmd=REGITSTER;
    strcpy(usernameInfo.argument,username);
    usernameInfo.length=strlen(username);
    send(sockfd,&usernameInfo,sizeof(usernameInfo.cmd)+
         sizeof(usernameInfo.length)+usernameInfo.length,0);

    // 接收服务器的返回值 
    int exist=-1;
    recvn(sockfd,&exist,sizeof(exist));
    // 如果存在，直接退出
    if(exist==1){
      printf("Username Already Exists.\n");
      return 1;
    }
    // 用户名不存在，可以正常注册
    else{
      recvn(sockfd,&usernameInfo,sizeof(usernameInfo.cmd));
      recvn(sockfd,&usernameInfo.length,sizeof(usernameInfo.length));
      recvn(sockfd,usernameInfo.argument,usernameInfo.length);
      char salt[150]={0};
      strcpy(salt,usernameInfo.argument);
      // cip密文
      char *cip=crypt(password,salt);
      usernameInfo.cmd=REGITSTER;
      usernameInfo.length=strlen(cip);
      strcpy(usernameInfo.argument,cip);
      send(sockfd,&usernameInfo,sizeof(usernameInfo.cmd)+
           sizeof(usernameInfo.length)+usernameInfo.length,0);
      printf("Register success.\n");
    }
    return 0;
}

